<template>
  <div>
    <div style="margin: 10px 0;">

      <el-button type="primary" icon="el-icon-plus" @click="dialogVisible = true">新增</el-button>
      <el-input placeholder="请输入名查询" v-model="name" clearable style="width: 200px;margin-left: 5px"></el-input>
      <el-button type="primary" icon="el-icon-search" style="margin-left: 5px" @click="search">查询</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" @selection-change="handleSelectionChange"
              :header-cell-style="{background:'#e7e8ef',color:'#4f5257'}"
              fixed border>
      <el-table-column
          prop="id"
          type="selection"
          width="40">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="100">
      </el-table-column>
      <el-table-column prop="name" label="角色名称" >
      </el-table-column>
      <el-table-column prop="mark" label="唯一标识" >
      </el-table-column>
      <el-table-column prop="description" label="角色描述" >
      </el-table-column>
      <el-table-column
          label="操作"
          width="280">
        <template slot-scope="scope">
          <el-button type="info" size="mini" class="el-icon-menu" @click="selectMenu(scope.row)">分配菜单</el-button>
          <el-button type="success" class="el-icon-edit" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button type="danger" size="mini" class="el-icon-remove-outline" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog
        title="分配菜单"
        :visible.sync="menuDialogVisible"
        width="30%"
        :before-close="handleClose">
      <el-tree
          :props="props"
          :data="menuData"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expends"
          :default-checked-keys="checks"
          >
        <span class="custom-tree-node" slot-scope="{node,data}">
          <span><i :class="data.icon">{{data.name}}</i></span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
            <el-button @click="menuDialogVisible = false">取 消</el-button>
             <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog
        title="角色信息"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">

      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="角色名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="唯一标识">
          <el-input v-model="form.mark"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
             <el-button type="primary" @click="save">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data(){
    return{
      name: '',
      tableData:[],
      currentPage: 4,
      pageNum:0,
      pageSize:5,
      total:0,
      dialogVisible: false,
      menuDialogVisible: false,
      form: {},
      ids:[],
      multipleSelection: [],
      //菜单分配
      menuData: [],
      props: {
        label: 'name'
      },
      expends: [],
      checks: [],
      roleId: 0,
      roleMark: ''
    }
  },
  created() {
    this.load()
  },
  methods:{
    reset(){
      this.address="";
      this.phone="";
      this.nickName="";
      this.load()
      this.$message({
        message: '重置成功',
        type: 'success'
      });
    },
    search(){
      if (this.address!='' || this.nickName!='' || this.phone!=''){
        this.load()
        this.$message({
          message: '查询成功',
          type: 'success'
        });
      }else{
        this.$message({
          message: '请输入查询内容',
          type: 'warning'
        });
      }
    },
    load(){
      this.request.get("/role/page",{
            params:{
              pageNum:this.pageNum,
              pageSize:this.pageSize,
              name: this.name
            }
          }
      ).then(res =>{
        this.tableData=res.data.records
        this.total=res.data.total
      })

    },
    save(){
      this.request.post("/role",this.form).then(res => {
        if (res.code === 200){
          this.$message.success("保存成功")
          this.dialogVisible=false
          this.form={}
          this.load()
        }else {
          this.$message.error(res.message)
        }
      })
    },
    saveRoleMenu(){
      this.request.post("/role/roleMenu/"+this.roleId,this.$refs.tree.getCheckedKeys()).then(res =>{
       if (res.code === 200){
         this.$message.success("分配成功")
         this.menuDialogVisible = false
        if (this.roleMark === 'ROLE_ADMIN'){
          //管理员分配完菜单重新登录一下
          this.$store.commit("resetSys")
        }
       }else {
         this.$message.error("分配失败")
       }
      })
    },
    handleEdit(row) {
      this.form=row
      this.dialogVisible=true
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    handleDelete(index, row) {
      this.request.delete("/role/"+(index,row).id).then(res=>{
        if (res.code === 200){
          this.load()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      })
    },
    delBatch(){
      let ids = this.multipleSelection.map(v =>v.id)
      if (ids.length!=0){
        this.$confirm('你正在进行批量删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request.post("/role/batch/", ids).then(res => {
            if (res.data){
              this.load()
              this.$message({
                type: 'success',
                message: '批量删除成功!'
              });
            }else {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else {
        this.$message.warning("请选择删除记录")
      }
    },
    /**
     * 选择框
     * */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      for (let i=1; i<=val; i++)
        console.log(this.multipleSelection[i])
    },
    /**
     * 自定义操作列
     * @param index
     * @param row
     */


    handleSizeChange(val) {
      this.pageSize = val;
      this.load()
    },
    handleCurrentChange(val) {
      this.pageNum=val
      this.load()
    },
    //分配菜单
    selectMenu(role){
      this.menuDialogVisible = true
      this.roleId = role.id
      this.roleMark = role.mark
      //请求菜单数据
      this.request.get("/menu").then(res =>{
        this.menuData = res.data
        //把后台返回的菜单数据处理成ID数组
        this.expends = this.menuData.map(v => v.id)

      })

      this.request.get("/role/roleMenu/"+this.roleId).then(res =>{
        this.checks = res.data

        this.request.get("/menu/ids").then(r =>{
          const ids = r.data
          ids.forEach(id =>{
            if (!this.checks.includes(id)){
              this.$refs.tree.setChecked(id,false)
            }
          })
        })
      })
    },
  }
}
</script>

<style scoped>

</style>